﻿namespace MobileTrack.Web.Controllers
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using System.Web.Security;
    using MobileTrack.Core.Data;
    using MobileTrack.Web.ViewModels;

    ////[RequireHttps]
    public class AccountController : BaseController
    {
        public AccountController(IRepositories repositories, MembershipProvider membershipProvider, RoleProvider roleProvider)
            : base(repositories, membershipProvider, roleProvider)
        {
        }

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            this.ViewBag.ReturnUrl = returnUrl;
            return this.View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if ((model != null) && this.ModelState.IsValid)
            {
                if (this.MembershipProvider.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (this.Url.IsLocalUrl(returnUrl))
                    {
                        return this.Redirect(returnUrl);
                    }
                    else
                    {
                        return this.RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    this.ModelState.AddModelError(string.Empty, "El nombre de usuario o contraseña es incorrecto.");
                }
            }

            // If we got this far, something failed, redisplay form.
            return this.View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return this.RedirectToAction("Index", "Home");
        }

        public ActionResult ChangePassword()
        {
            return this.View();
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if ((model != null) && this.ModelState.IsValid)
            {
                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = this.MembershipProvider.GetUser(this.User.Identity.Name, userIsOnline: true);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    this.Profile.Initialized = true;
                    this.Profile.Save();

                    return this.RedirectToAction("Index", "Home");
                }
                else
                {
                    this.ModelState.AddModelError(string.Empty, "La contraseña actual es incorrecta o la nueva contraseña es inválida.");
                }
            }

            // If we got this far, something failed, redisplay form.
            return this.View(model);
        }

        private IEnumerable<string> GetErrorsFromModelState()
        {
            return this.ModelState.SelectMany(x => x.Value.Errors.Select(error => error.ErrorMessage));
        }
    }
}
